// @version gowebstatic 0.1
// @author xiaotangren  <unphp@qq.com>
// @data 2014-07-21

package main

import (
	"bufio"
	"fmt"
	"os"
	"time"

	"git.oschina.net/unphp/go-utils/log"
)

func main() {

	//启动系统日志
	listen(RootPath+"/"+ConfData.Get("core", "logpath").String(), Log)
	//系统结束前执行的
	defer func() {
		for _, fun := range ServerDeferFuncSlice {
			fun()
		}
	}()

}

//监听服务运行状态，记录服务日志。
func listen(logpath string, Log *log.Log) {
	oldStr := time.Now().Format("2006-01-02")
	files := openLogFile(logpath, oldStr)
	var logwriter *bufio.Writer
	logwriter = bufio.NewWriter(files)
	logwriter.WriteString("-------------------服务开始启动--------------------" + "\r\n")
	logwriter.WriteString("Date:" + time.Now().Format("2006-01-02 15:04:05") + "\r\n")
	logwriter.Flush()
	for {
		nowStr := time.Now().Format("2006-01-02")
		if nowStr != oldStr {
			oldStr = nowStr
			files.Close()
			files = openLogFile(logpath, nowStr)
			logwriter = bufio.NewWriter(files)
		}
		select {
		case msg := <-Log.ChanLogMsg:
			for _, v := range msg {
				fmt.Println(v)
				logwriter.WriteString(v + "\r\n")
			}
			logwriter.Flush()
		default:
		}
		time.Sleep(1 * time.Second)
	}
}

func openLogFile(logpath, n string) *os.File {
	logPath := logpath + "/syslog"
	//fmt.Println(logPath)
	os.MkdirAll(logPath, 0755)
	files, _ := os.OpenFile(logPath+"/"+n, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	return files
}
